package com.cqc.manage.service.Imp.user;

import com.cqc.manage.entity.User;
import com.cqc.manage.error.ErrorEnum;
import com.cqc.manage.error.GException;
import com.cqc.manage.repositories.UserRepositories;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * 用户服务
 */
@Service
public class UserService {

    private static Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepositories userRepositories;

    /**
     * 添加用户
     * @param user
     * @return
     */
    public User addUser(User user){
        LOG.debug("添加用户，参数:{}",user);
        // 数据校验
        checkUser(user);
        // 设置默认值
        setDefault(user);
        User save = userRepositories.save(user);
        LOG.debug("添加用户结果:{}",save);
        return save;
    }

    /**
     * 通过用户id查询用户
     * @param id
     * @return
     */
    public User queryByUserId(String id){
        Optional<User> byId = userRepositories.findById(id);
        return byId.get();
    }

    /**
     * 通过account和password查询用户
     * @param userAccount
     * @param userPassword
     * @return
     */
    public User findByUserAccountAndPassword(String userAccount,String userPassword){
        User userByUserNameAndAndUserPassword = userRepositories.findUserByUserAccountAndUserPassword(userAccount, userPassword);
        Assert.notNull(userByUserNameAndAndUserPassword, ErrorEnum.USER_NOT_FIND.getCode());
        if (!userByUserNameAndAndUserPassword.getUserStatus()){
            Assert.isTrue(userByUserNameAndAndUserPassword.getUserStatus(),ErrorEnum.USER_STATUS_FALSE.getCode());
        }
        return userByUserNameAndAndUserPassword;
    }

    /**
     * 通过用户名查询用户
     * @param userName
     * @return
     */
    public User findByUserName(String userName){
        return userRepositories.findUserByUserName(userName);
    }

    /**
     * 通过用户账户查询用户
     * @param userAccount
     * @return
     */
    public User findByUserAccount(String userAccount){
        return userRepositories.findUserByUserAccount(userAccount);
    }

    /**
     * 更新用户:save方法也具有update的功能，加上事务的注解，Transactional
     * @param user
     * @return
     */
    @Transactional
    public User updateUser(User user){
        LOG.debug("更新的用户:{}",user);
        checkUser(user);
        Optional<User> byId = userRepositories.findById(user.getUserId());  // 通过主键id查询用户是否存在
        if (!byId.isPresent()){
            return null;
        }
        User save = userRepositories.save(user);
        return save;
    }

    /**
     * 更改用户状态
     * @param user
     * @return
     */
    @Transactional
    public User setUserStatus(User user){
        User save = userRepositories.save(user);
        return save;
    }

    private void setDefault(User user) {
//        user.setUserAccount(user.getUserName());
        user.setUserId(UUID.randomUUID().toString().replace("-",""));
        user.setCreateAt(new Date());
        user.setUserStatus(false);
    }

    /**
     * 存入用数据进行检查
     * @param user
     */
    private void checkUser(User user) {
//        Assert.notNull(user.getUserAccount(), ErrorEnum.LACK_USER_ACCOUNT.getCode());
        Assert.notNull(user.getUserName(),ErrorEnum.LACK_USER_USERNAME.getCode());
        Assert.notNull(user.getUserPassword(),ErrorEnum.LACK_USER_USERPASSWORD.getCode());
        Assert.isNull(userRepositories.findUserByUserAccount(user.getUserAccount()),ErrorEnum.USER_EXIST.getCode());
//        if (userRepositories.findUserByUserName(user.getUserName()) != null){
//            throw new GException(203,"用户名存在");
//        }
    }

    /**
     * 分页查询
     * @param pageable
     * @return
     */
    public Page<User> query(Pageable pageable){

        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                return null;
            }
        };
        Page<User> all = userRepositories.findAll(specification, pageable);
        return all;
    }


    /**
     * 删除用户
     * @param id 用户id
     */
    public void delteUser(String id){
        userRepositories.deleteById(id);
    }

    /**
     * 获取所有用户的用户名
     */
    public List<Map<String,String>> getAllUserName(){
        List<User> all = userRepositories.findAll();
        List<Map<String,String>> list_map = new ArrayList<>();
        for(User user :all){
            Map<String,String> map = new HashMap<>();
            map.put("value",user.getUserId());
            map.put("label",user.getUserName());
            list_map.add(map);
        }
        return list_map;
    }

}